package com.yswl.pri.fun;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.huxq17.swipecardsview.BaseCardAdapter;
import com.huxq17.swipecardsview.SwipeCardsView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yswl.pri.R;
import com.yswl.pri.common.ToolbarMFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import yswl.com.klibrary.http.CallBack.HttpCallback;
import yswl.com.klibrary.http.HttpClientProxy2;
import yswl.com.klibrary.util.L;
import yswl.com.klibrary.util.MKeyBoardUtils;
import yswl.com.klibrary.util.MUrlUtil;

public class FunFragment extends ToolbarMFragment implements HttpCallback<String> {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_joke, container, false);
    }

    RefreshLayout srlView;
    SwipeCardsView mSwipCard;
    JokeAdapter mAdapter;


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
    }

    @Override
    protected String getToolbarTitle() {
        return "笑话十则";
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        srlView = view.findViewById(R.id.refreshLayout);
        srlView.setEnableAutoLoadMore(false);
        srlView.setEnableLoadMore(false);
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                requestData();
            }
        });
        mSwipCard = view.findViewById(R.id.swipCardsView);
        //保留最后一张卡片，具体请看[#9](https://github.com/huxq17/SwipeCardsView/issues/9)
//        mSwipCard.retainLastCard(true);
        mAdapter = new JokeAdapter(mContext);
        mSwipCard.setCardsSlideListener(new SwipeCardsView.CardsSlideListener() {
            @Override
            public void onShow(int index) {
                L.e("tag", " onShow index " + index);
            }

            @Override
            public void onCardVanish(int index, SwipeCardsView.SlideType type) {
                L.e("tag", "onCardVanish index " + index);
                if (index == mAdapter.getCount() - 1) {
                    srlView.setEnableRefresh(true);
                    srlView.autoRefresh();
                }
            }

            @Override
            public void onItemClick(View cardImageView, int index) {
                L.e("tag", "onItemClick index " + index);
            }
        });
        srlView.autoRefresh();
    }

    void requestData() {
        String url = MUrlUtil.getUrl(R.string.url_joke2);
        HttpClientProxy2.getInstance().getAsyn(url, 1, null, this);
    }


    @Override
    public void onSucceed(int requestId, String result) {
        srlView.finishRefresh(true);
        srlView.setEnableRefresh(false);
        if (TextUtils.isEmpty(result)) return;
        List<JokeInfo> data = JokeInfo.jsonToList(result);
        mAdapter.setList(data);
        mSwipCard.setAdapter(mAdapter);
    }

    @Override
    public void onFail(int requestId, String errorMsg) {
        srlView.finishRefresh(true);
    }


    class JokeAdapter extends BaseCardAdapter<JokeInfo> {

        private List<JokeInfo> datas;
        private Context context;

        public JokeAdapter(Context context) {
            this.datas = new ArrayList<>();
            this.context = context;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public int getCardLayoutId() {
            return R.layout.adapter_joke_item;
        }

        @Override
        public void onBindData(final int position, View cardview) {
            if (datas == null || datas.size() == 0) {
                return;
            }
            final TextView tvJoke = cardview.findViewById(R.id.tv_joke);
            TextView tvCpoy = cardview.findViewById(R.id.tv_copy);
            TextView tvShare = cardview.findViewById(R.id.tv_share);

            final JokeInfo joke = datas.get(position);
            tvJoke.setText(joke.getJokeContent());

            tvCpoy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MKeyBoardUtils.copy(joke.getJokeContent(), context);
                    Toast.makeText(context, "已复制", Toast.LENGTH_SHORT).show();
                }
            });
            tvShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    shareTextAndImage(context, "", joke.getJokeContent(), null);
                }
            });

        }

        public void setList(List<JokeInfo> list) {
            this.datas = list;
        }

        @Override
        public int getVisibleCardCount() {
            return 4;
        }
    }


    /**
     * 分享功能
     *
     * @param context  上下文
     * @param msgTitle 消息标题
     * @param msgText  消息内容
     * @param imgPath  图片路径，不分享图片则传null
     */
    public static void shareTextAndImage(Context context, String msgTitle, String msgText, String imgPath) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        if (imgPath == null || imgPath.equals("")) {
            intent.setType("text/plain"); // 纯文本
        } else {
            File f = new File(imgPath);
            if (f != null && f.exists() && f.isFile()) {
                intent.setType("image/jpg");
                Uri fileUri = null;
                if (Build.VERSION.SDK_INT >= 24) {
                    fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", f);
                } else {
                    fileUri = Uri.fromFile(f);
                }
                intent.putExtra(Intent.EXTRA_STREAM, fileUri);
            }
        }
        intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
        intent.putExtra(Intent.EXTRA_TEXT, msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(intent, "分享到"));
    }

}
